#!/opt/bin/python
import sys
import re
import socket
import datetime
import smtplib
import shutil

local_ip = "192.168.155.134"
white_list = "whitelist.txt"
black_list = "blacklist.txt"
EX_OK, EX_BANNED, EX_UNKNOWN = range(3)
ex = EX_OK
banned = ['PASS', 'BANNED', 'UNKNOWN']
target_ip = ""

def send(file, sender, receiver):
	server = smtplib.SMTP('localhost', 10028)
	f = open(file)
	msg = f.read()
	f.close()
	#print "%s, %s" % (sender, receiver)
	server.sendmail(sender, receiver, msg)
	server.quit()

def telnet(ip):
	port = [3128, 8080, 1080]

	portopen = False
	for p in port:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			s.settimeout(2)
			s.connect((ip, p))
			portopen = p
		except socket.error, msg:
			pass
		finally:
			s.close()

	if portopen != False:
		# print " open on %d" % portopen
		
		f = open(black_list, 'a')
		print >>f, ip
		print >>log, "%s IP %s BLACKLISTED (port %d)" % (datetime.datetime.now(), target_ip, portopen)
		f.close()
		return EX_BANNED
	else:
		return EX_OK

def check(ip):
	global ex, white_list

	# Check white list
	whitelisted = False
	f = open(white_list)

	for line in f:
		line = line.strip()
		if ip == line:
			whitelisted = True
	f.close()

	# Check black list
	blacklisted = False
	f = open(black_list)

	for line in f:
		line = line.strip()
		if ip == line:
			blacklisted = True

	if whitelisted:
		# print "!!! whitelisted"
		ex = EX_OK
	elif blacklisted:
		# print "!!! blacklisted"
		ex = EX_BANNED
	else:
		# print "checking..."
		ex = telnet(ip)

def start(file):
	global ex, local_ip, target_ip

	spam = False

	m = re.compile('Received: from ([^ ]+) \(([^)]+)\)')
	mip = re.compile('\[([^ ]+)\]')

	f = open(file)
	stack = []

	for line in f:
		line = line.strip()
		result = m.search(line)

		# match for "Received: from"
		if result != None:
			ipresult = mip.search(result.group(2))
			# Get the ip
			if ipresult != None:
				ip = ipresult.group(1)
				stack.append('%s' % ip)

		# only test ip that are flagged SPAM
		if line == "X-Spam-Flag: YES":
			spam = True
	
	f.close()

	next = False
	immediate = ""
	# Find the record next to local ip
	for ip in stack:
		if next == True:
			immediate = ip
			next = False

		if ip == local_ip:
			next = True

	target_ip = immediate
	if spam:
		check(immediate)
		print >>log, "%s IP %s %s (%s)" % (datetime.datetime.now(), target_ip, banned[ex], file)
	else:
		print >>log, "%s IP %s NOT SPAM" % (datetime.datetime.now(), target_ip)

log = open("log", 'a')
# print >>log, "%s DEBUG, %s" % (datetime.datetime.now(), sys.argv)
filename = sys.argv[1]
sender = sys.argv[2]
receiver = sys.argv[3]
# print >>log, "%s INVOKED, %s, %s, %s" % (datetime.datetime.now(), filename, sender, receiver)

start(filename)

log.close()

if ex == EX_OK:
	send(filename, sender, receiver)
else:
	shutil.copy(filename, "dropped.%s" % filename)

sys.exit(ex)
